package main

/**
runtime/pprof：非httpServer环境，使用go tool pprof分析

profile: 调用pprof.StartCPUProfile或者pprof.StopCPUProfile生成和写入文件
heap: 调用pprof.WriteHeapProfile， dump堆内存，写入文件。使用go tool pprof分析
block/mutex/groutine: pprof.Lookup(pprofName)查找profile, 然后调用profile.WriteTo写入
*/

import (
	"fmt"
	"os"
	"runtime/pprof"
	"runtime/trace"
	"time"
)

type Func func()

//耗时耗性能方法
func Runtime() {
	go func() {
		for {
			Cost1()
		}
	}()
	go func() {
		for {
			Cost2()
		}
	}()

	go func() {
		for {
			TestMutex()
		}
	}()

	go func() {
		TestBlock()
	}()
}

func WriteCPU(path string, seconds int) {
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()

	pprof.StartCPUProfile(file)
	time.Sleep(time.Duration(seconds) * time.Second)
	pprof.StopCPUProfile()
}

func WriteMem(path string) {
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()

	pprof.WriteHeapProfile(file)
}

func WriteBlock(path string) {
	WritePProfTo("block", path)
}

func WriteMutex(path string) {
	WritePProfTo("mutex", path)
}

func WriteGoRoutine(path string) {
	WritePProfTo("goroutine", path)
}

func WriteThreadCreate(path string) {
	WritePProfTo("threadcreate", path)
}

func WritePProfTo(pprofName, path string) {
	profile := pprof.Lookup(pprofName)

	f, err := os.Create(path)
	if err != nil {
		fmt.Println(err)
	}
	defer f.Close()

	profile.WriteTo(f, 0)
}

func WriteTrace(path string, seconds int) {
	f, err := os.Create(path)
	if err != nil {
		fmt.Println(err)
	}
	trace.Start(f)
	time.Sleep(time.Duration(seconds) * time.Second)
	trace.Stop()
}
